package com.china08.yxyapi.service.res.statistics.impl;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.entity.db.res.YxyArea;
import com.china08.yxyapi.entity.db.statistics.AreaResourceReport;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceDay;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceMonth;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceReport;
import com.china08.yxyapi.entity.mg.statistics.SchoolUploadResourceWeekOfYearReport;
import com.china08.yxyapi.entity.mg.statistics.UserUploadResourceTotal;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.statistics.AreaResourceReportRepository;
import com.china08.yxyapi.repository.db.yxy.YxyAreaRepository;
import com.china08.yxyapi.repository.mg.SchoolUploadResourceMonthRepository;
import com.china08.yxyapi.repository.mg.SchoolUploadResourceReportRepository;
import com.china08.yxyapi.repository.mg.statistics.SchoolUploadResDayRepository;
import com.china08.yxyapi.repository.mg.statistics.SchoolUploadResourceWeekOfYearReportRepository;
import com.china08.yxyapi.repository.mg.statistics.UserUploadResourceTotalRepository;
import com.china08.yxyapi.service.res.statistics.IResourceStatisticsEs;
import com.china08.yxyapi.util.DateUtils;
import com.china08.yxyapi.util.SendEmailUtil;

@Service
public class ResourceStatisticsEsImpl implements IResourceStatisticsEs {

    private static final Logger LOGGER = Logger.getLogger(ResourceStatisticsEsImpl.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private AreaResourceReportRepository areaResourceReportRepository;

    @Autowired
    private SchoolUploadResourceReportRepository schoolUploadResourceReportRepository;

    @Autowired
    private SchoolUploadResDayRepository schoolUploadResDayRepository;

    @Autowired
    private YxyAreaRepository yxyAreaRepository;

    @Autowired
    private UserUploadResourceTotalRepository userUploadResourceTotalRepository;

    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    MongoTemplate mt;

    @Autowired
    private SchoolUploadResourceMonthRepository schoolUploadResourceMonthRepository;

    @Autowired
    private SchoolUploadResourceWeekOfYearReportRepository schoolUploadResourceWeekOfYearReportRepository;

    /**
     * 
     * 学校资源总数统计
     * 
     */
    @Override
    public void schoolStatisticsTotalEs(Integer date) {
        Long start = System.currentTimeMillis();
        // ----------------------start此方法是因为学校后来被移动过地区（学校从哈尔滨移动到北京）导致区县和学校两边统计的数据不一样，举例：哈尔滨的市辖区的学校会把北京的市辖区的学校覆盖-----------------------//
        // ----第一步对区进行分组-------//
        /*
         * BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
         * TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
         * "yx14"); TermQueryBuilder builderType = new
         * TermQueryBuilder("isDelete", 0);
         * boolQueryBuilder.mustNot(builderType2);
         * boolQueryBuilder.must(builderType); SearchRequestBuilder
         * searchRequestBuilder =
         * et.getClient().prepareSearch("yxy_res").setTypes("resource");
         * searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
         * TermsBuilder gradeTermsBuilder1 =
         * AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(
         * 25000); searchRequestBuilder.addAggregation(gradeTermsBuilder1);
         * SearchResponse sr =
         * searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet()
         * ; Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
         * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
         * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
         * Map<String, Object> map = new HashMap<String, Object>(); while
         * (gradeBucketIt.hasNext()) { Bucket gradeBucket =
         * gradeBucketIt.next(); String key = (String) gradeBucket.getKey();
         * long value = gradeBucket.getDocCount(); map.put(key, value); }
         * 
         * //------第二步对每个区下的学校进行分组--------// Map<String, Object> mapschoolId =
         * new HashMap<String, Object>(); for (String dis : map.keySet()) {
         * BoolQueryBuilder boolQueryBuilder1 = new BoolQueryBuilder();
         * TermQueryBuilder builderType22 = new TermQueryBuilder("typeId",
         * "yx14"); TermQueryBuilder builderType1 = new
         * TermQueryBuilder("isDelete", 0);
         * boolQueryBuilder1.mustNot(builderType22);
         * boolQueryBuilder1.must(builderType1); TermQueryBuilder builderTypedis
         * = new TermQueryBuilder("districtCode", dis);
         * boolQueryBuilder1.must(builderTypedis); SearchRequestBuilder
         * searchRequestBuilder1 =
         * et.getClient().prepareSearch("yxy_res").setTypes("resource");
         * searchRequestBuilder1.setSearchType(SearchType.QUERY_THEN_FETCH);
         * TermsBuilder gradeTermsBuilder11 =
         * AggregationBuilders.terms("phaseIdAgg1").field("uploaderSchoolId").
         * size(25000);
         * searchRequestBuilder1.addAggregation(gradeTermsBuilder11);
         * SearchResponse sr1 =
         * searchRequestBuilder1.setQuery(boolQueryBuilder1).execute().actionGet
         * (); Map<String, Aggregation> aggMap1 = sr1.getAggregations().asMap();
         * StringTerms gradeTerms1 = (StringTerms) aggMap1.get("phaseIdAgg1");
         * Iterator<Bucket> gradeBucketIt1 =
         * gradeTerms1.getBuckets().iterator(); while (gradeBucketIt1.hasNext())
         * { Bucket gradeBucket1 = gradeBucketIt1.next(); String key1 = (String)
         * gradeBucket1.getKey(); long value1 = gradeBucket1.getDocCount();
         * mapschoolId.put(key1, value1); } }
         */
        // -------------------------end-------------------------//

        // TermsBuilder gradeTermsBuilder =
        // AggregationBuilders.terms("phaseIdAgg1").field("uploaderSchoolId").size(25000);

        /*
         * for (String key : map.keySet()) { resourceModel = new
         * ResourceModel(); resourceModel.areaName = key;
         * resourceModel.areaCount = Long.parseLong(map.get(key).toString());
         * resourceModelLst.add(resourceModel); }
         */

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder1 = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder1);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        // 统计资源共享数量
        Map<String, Object> map2 = this.staticsShareCount();// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计微课总共数量
        Map<String, Object> map3 = this.staticsWeikeCount();
        // 统计微课共享数量
        Map<String, Object> map4 = this.staticsWeikeShareCount();

        // 返回 map里统计的资源总量
        Map<String, Object> mapschoolId2 = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            mapschoolId2.put(key, value);
        }
        SchoolUploadResourceReport schoolUploadResourceReport = null;
        for (String key : map.keySet()) {
            schoolUploadResourceReport = schoolUploadResourceReportRepository.findBySchoolId(key);
            if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                if (schoolUploadResourceReport != null) {
                    // schoolUploadResourceReport
                    // .setId(schoolUploadResourceReportRepository.findBySchoolId(key).getId());
                } else {
                    schoolUploadResourceReport = new SchoolUploadResourceReport();
                    schoolUploadResourceReport.setId(key);
                    schoolUploadResourceReport.setSchoolId(key);

                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {

                            schoolUploadResourceReport.setSchoolNick(reList.getBody().get("schoolNick"));
                            schoolUploadResourceReport.setAreaIdProvince(reList.getBody().get("areaIdProvince"));
                            schoolUploadResourceReport.setAreaNameProvince(reList.getBody().get("areaNameProvince"));
                            schoolUploadResourceReport.setAreaIdCity(reList.getBody().get("areaIdCity"));
                            schoolUploadResourceReport.setAreaNameCity(reList.getBody().get("areaNameCity"));
                            schoolUploadResourceReport.setAreaIdDistrict(reList.getBody().get("areaIdDistrict"));
                            schoolUploadResourceReport.setAreaNameDistrict(reList.getBody().get("areaNameDistrict"));

                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                    if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                        try {
                            ResponseEntity<List<String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/type/id/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
                            });
                            if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                                schoolUploadResourceReport.setStage(reList.getBody());
                            }
                        } catch (Exception e) {
                            LOGGER.info("错误日志" + e.getMessage());
                        }

                    }
                }

            }

            schoolUploadResourceReport.setResCount(Long.valueOf(map.get(key).toString()));// 资源总数量
            for (String key2 : map2.keySet()) {
                if (key.equals(key2)) {
                    schoolUploadResourceReport.setShareResCount(Long.valueOf(map2.get(key2).toString())); // 资源共享数量
                }
            }
            if (schoolUploadResourceReport.getShareResCount() == null) {
                schoolUploadResourceReport.setShareResCount(0l);
            }
            for (String key3 : map3.keySet()) {
                if (key.equals(key3)) {
                    schoolUploadResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).toString())); // 微课总共数量
                }
            }
            if (schoolUploadResourceReport.getWeikeCount() == null) {
                schoolUploadResourceReport.setWeikeCount(0l);
            }
            for (String key4 : map4.keySet()) {
                if (key.equals(key4)) {
                    schoolUploadResourceReport.setShareWeikeCount(Long.valueOf(map4.get(key4).toString())); // 微课共享数量
                }
            }
            if (schoolUploadResourceReport.getShareWeikeCount() == null) {
                schoolUploadResourceReport.setShareWeikeCount(0l);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            schoolUploadResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            schoolUploadResourceReportRepository.save(schoolUploadResourceReport);
        }

        Long end = System.currentTimeMillis();
        LOGGER.info(" --------- yyy " + (end - start));// 运行完此方法需要134毫秒
        LOGGER.info("xuexiaochangdu--" + map.size());

    }

    /**
     * 统计用户资源数量
     */
    @Override
    public void userSchoolStatistics(Integer date) {
        Long start = System.currentTimeMillis();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        /*
         * TermQueryBuilder builderTypes = new
         * TermQueryBuilder("uploaderSchoolId",
         * "9b9560b519c3930a711137560141ca67");
         * boolQueryBuilder.must(builderTypes);
         */
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        // ----ff8080815b9da441015b9ebb6f7a0001 = 157---//
        // ----ff8080815b9da441015b9ebb6f7a0001=8 ----//
        /*
         * TermQueryBuilder builderDel = new
         * TermQueryBuilder("uploaderSchoolId",
         * "9b9560b519c3930a711137560141ca67");
         * boolQueryBuilder.must(builderDel); // TermQueryBuilder builderDel22 =
         * new TermQueryBuilder("viewScope", 0); //
         * boolQueryBuilder.mustNot(builderDel22); SearchQuery query = new
         * NativeSearchQueryBuilder().withQuery(boolQueryBuilder).build();
         * 
         * // 查询出来的总数量 long allCount =
         * et.count(query,ElasticYxyResResource.class); List<Long> longCount =
         * new ArrayList<Long>(); longCount.add(allCount);
         */

        /*
         * TermsBuilder uploaderIdTermsBuilder =
         * AggregationBuilders.terms("uploaderIdAgg").field("uploaderSchoolId").
         * size(25000);
         * searchRequestBuilder.addAggregation(uploaderIdTermsBuilder);
         * SearchResponse sr =
         * searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet()
         * ; Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
         * StringTerms uploaderSchoolIdTerms = (StringTerms)
         * aggMap.get("uploaderIdAgg"); Iterator<Bucket>
         * uploaderSchoolIdBucketIt =
         * uploaderSchoolIdTerms.getBuckets().iterator(); Map<String, Object>
         * mapZong1 = new HashMap<String, Object>();
         * while(uploaderSchoolIdBucketIt.hasNext()) {
         * 
         * Bucket classBucket = uploaderSchoolIdBucketIt.next(); long value =
         * classBucket.getDocCount(); String key = (String)classBucket.getKey();
         * mapZong1.put(key, value); }
         */

        Map<String, Object> mapZong = new HashMap<String, Object>();

        TermsBuilder uploaderSchoolIdTermsBuilder = AggregationBuilders.terms("uploaderSchoolIdAgg").field("uploaderSchoolId").size(25000);
        TermsBuilder uploaderIdTermsBuilder = AggregationBuilders.terms("uploaderIdAgg").field("uploaderId").size(25000);
        uploaderSchoolIdTermsBuilder.subAggregation(uploaderIdTermsBuilder);
        searchRequestBuilder.addAggregation(uploaderSchoolIdTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms uploaderSchoolIdTerms = (StringTerms) aggMap.get("uploaderSchoolIdAgg");
        List<Bucket> uploaderSchoolIdBucket = uploaderSchoolIdTerms.getBuckets();
        Object[] objs = null;
        LOGGER.info("school_count:" + uploaderSchoolIdBucket.size());
        Iterator<Bucket> uploaderSchoolIdBucketIt = uploaderSchoolIdBucket.iterator();
        while (uploaderSchoolIdBucketIt.hasNext()) {
            Bucket gradeBucket = uploaderSchoolIdBucketIt.next();
            LOGGER.info(gradeBucket.getKey() + "学校" + gradeBucket.getDocCount() + "资源数。");
            StringTerms teaTerms = (StringTerms) gradeBucket.getAggregations().asMap().get("uploaderIdAgg");
            List<Bucket> teaBucket = teaTerms.getBuckets();
            objs = new Object[2];
            objs[0] = gradeBucket.getKey();// 学校id
            LOGGER.info("school_id: " + objs[0]);
            LOGGER.info("user_count: " + teaBucket.size());
            Iterator<Bucket> teaBucketIt = teaBucket.iterator();
            while (teaBucketIt.hasNext()) {
                Bucket cBucket = teaBucketIt.next();
                long value = cBucket.getDocCount();
                objs[1] = cBucket.getKey(); // 教师id
                LOGGER.info(gradeBucket.getKey() + "学校" + objs[1] + "教师。" + " 有多少资源：" + value);
                mapZong.put(objs[0] + "," + objs[1], value);
                objs[1] = null;
            }
            System.out.println();
        }
        // 用户共享资源数量
        Map<String, Object> map2 = this.userStaticsShareCount();
        UserUploadResourceTotal userUploadResourceTotal = null;
        String userId = null;
        String schoolId = null;
        for (String shuliang : mapZong.keySet()) {
            Object[] objs2 = shuliang.split(",");
            userId = objs2[1].toString();
            schoolId = objs2[0].toString();
            if (StringUtils.isNotBlank(shuliang)) {// 判断用户id是否空
                userUploadResourceTotal = userUploadResourceTotalRepository.findOne(userId + schoolId);
                if (userUploadResourceTotal != null) {
                    // userUploadResourceTotal.setId(userUploadResourceTotalRepository.findByUserId(userId).getId());
                } else {
                    userUploadResourceTotal = new UserUploadResourceTotal();
                    System.out.println();
                    userUploadResourceTotal.setId(userId + schoolId);
                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/user/username/" + userId, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                            userUploadResourceTotal.setUserNick(reList.getBody().get("nickname"));
                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                    if (StringUtils.isNotBlank(schoolId)) {// 判断学校id是否空
                        try {
                            ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + schoolId, HttpMethod.GET, null,
                                    new ParameterizedTypeReference<Map<String, String>>() {
                                    });
                            if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                                userUploadResourceTotal.setSchoolNick(reList.getBody().get("schoolNick"));
                            }
                        } catch (Exception e) {
                            LOGGER.info("错误日志" + e.getMessage());
                        }
                    }
                }

                userUploadResourceTotal.setUserId(userId);
                userUploadResourceTotal.setSchoolId(schoolId);
            }
            userUploadResourceTotal.setStatisticsDate(DateUtils.getBeforeDay(new Date()));

            // 用户总共资源数量
            userUploadResourceTotal.setResCount(Long.valueOf(mapZong.get(shuliang).toString()));
            if (userUploadResourceTotal.getResCount() == null) {
                userUploadResourceTotal.setResCount(0l);
            }
            // 用户共享资源数量
            for (String key2 : map2.keySet()) {
                if (shuliang.equals(key2)) {
                    userUploadResourceTotal.setShareResCount(Long.valueOf(map2.get(key2).toString()));
                }
            }
            if (userUploadResourceTotal.getShareResCount() == null) {
                userUploadResourceTotal.setShareResCount(0l);
            }
            if (userUploadResourceTotal.getWeikeCount() == null) {
                userUploadResourceTotal.setWeikeCount(0l);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userUploadResourceTotal.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            userUploadResourceTotalRepository.save(userUploadResourceTotal);
        }
        /*
         * List<UserUploadResourceTotal> userUploadIds =
         * userUploadResourceTotalRepository.findAll(); List<String>
         * userUploadId = new ArrayList<String>(); for (UserUploadResourceTotal
         * userUploadResourceTotal2 : userUploadIds) {
         * userUploadId.add(userUploadResourceTotal2.getId()); }
         * UserUploadResourceTotal userUploadResourceTo = null; for (String
         * string : userUploadId) { if (!mapZong.containsKey(string)) {
         * userUploadResourceTo =
         * userUploadResourceTotalRepository.findOne(string); if
         * (userUploadResourceTo.getResCount() == null) {
         * userUploadResourceTo.setResCount(0l); } if
         * (userUploadResourceTo.getShareResCount() == null) {
         * userUploadResourceTo.setShareResCount(0l); } if
         * (userUploadResourceTo.getWeikeCount() == null) {
         * userUploadResourceTo.setWeikeCount(0l); } if
         * (userUploadResourceTo.getShareWeikeCount() == null) {
         * userUploadResourceTo.setShareWeikeCount(0l); }
         * userUploadResourceTotalRepository.save(userUploadResourceTo); } }
         */
        // 统计用户微课总共数量
        this.userStaticsWeikeCount();

        Long end = System.currentTimeMillis();
        System.out.println(end - start);// 运行完此方法需要608毫秒
        LOGGER.info("yonghuchangdu--" + mapZong.size());

    }

    /**
     * 区域统计资源每天的数据
     * 
     * @param beforeDate
     * @throws ParseException
     */
    @Override
    public void ywStatisticsResourceAreaForDayEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        searchRequestBuilder.setQuery(boolQueryBuilder); // .setPostFilter(QueryBuilders.rangeQuery("createdDate").from(start1.getTime()).to(end1.getTime()));
        SearchResponse sr = searchRequestBuilder.execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 统计每天资源共享数量
        Map<String, Object> map2 = this.staticsShareDayCount(startDate, endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计每天微课总共数量
        // Map<String, Object> map3 = this.staticsWeikeDayCount(startDate,
        // endDate, beforeDate);
        // 统计每天微课共享数量
        // Map<String, Object> map4 = this.staticsWeikeShareDayCount(startDate,
        // endDate, beforeDate);

        // 返回 map里统计的资源总量
        Map<String, Object> map = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }

        AreaResourceReport areaResourceReport = null;
        // 每天的资源总量
        YxyArea yxyArea = null;
        for (String key : map.keySet()) {
            areaResourceReport = areaResourceReportRepository.findByIntDateAndAreaIdDistrict(beforeDate, key);
            // 首先判断当前区代码下面存在不存在
            if (areaResourceReport != null) {// 如果不等于空，就证明当前日期下的地区已经存在
                /*
                 * areaResourceReport .setId(areaResourceReport.getId());
                 */
            } else {
                areaResourceReport = new AreaResourceReport();
            }

            areaResourceReport.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
            areaResourceReport.setIntDate(beforeDate);
            areaResourceReport.setAreaIdDistrict(key); // 区代码
            yxyArea = yxyAreaRepository.findByAreaId(key);
            if (yxyArea != null) {
                areaResourceReport.setAreaNameDistrict(yxyArea.getAreaName()); // 区名称
                areaResourceReport.setAreaIdCity(yxyArea.getAreaPId()); // 市代码
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaNameCity(yxyArea.getAreaName()); // 市名称
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaIdProvince(yxyArea.getAreaId()); // 省代码
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaNameProvince(yxyArea.getAreaName());// 省名称
            }
            areaResourceReport.setResCount(Long.valueOf(map.get(key).toString())); // 资源总共
            for (String key2 : map2.keySet()) {
                if (key.equals(key2)) {
                    areaResourceReport.setShareResCount(Long.valueOf(map2.get(key2).toString()));// 资源共享
                }
            }
            if (areaResourceReport.getWeikeCount() == null) {
                areaResourceReport.setWeikeCount(0l);
            }
            if (areaResourceReport.getShareWeikeCount() == null) {
                areaResourceReport.setShareWeikeCount(0l);
            }
            /*
             * for (String key3 : map3.keySet()) { if (key.equals(key3)) {
             * areaResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).
             * toString()));// 微课总量 } } for (String key4 : map4.keySet()) { if
             * (key.equals(key4)) {
             * areaResourceReport.setShareWeikeCount(Long.valueOf(map4.get(key4)
             * .toString()));// 微课共享 } }
             */
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
            // HH:mm:ss");
            areaResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            areaResourceReportRepository.save(areaResourceReport);
        }
        this.ywStatisticsWeiKeAreaForDayEs(startDate, endDate, beforeDate);
    }

    /**
     * 区域统计微课每天的数据
     * 
     * @param beforeDate
     * @throws ParseException
     */
    private void ywStatisticsWeiKeAreaForDayEs(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        searchRequestBuilder.setQuery(boolQueryBuilder);// .setPostFilter(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()));
        SearchResponse sr = searchRequestBuilder.execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 统计每天资源共享数量
        // Map<String, Object> map2 = this.staticsShareDayCount(startDate,
        // endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计每天微课总共数量
        // Map<String, Object> map3 = this.staticsWeikeDayCount(startDate,
        // endDate, beforeDate);
        // 统计每天微课共享数量
        Map<String, Object> map4 = this.staticsWeikeShareDayCount(startDate, endDate, beforeDate);

        // 返回 map里统计的资源总量
        Map<String, Object> map = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }

        AreaResourceReport areaResourceReport = null;
        // 每天的资源总量
        YxyArea yxyArea = null;
        for (String key : map.keySet()) {
            areaResourceReport = areaResourceReportRepository.findByIntDateAndAreaIdDistrict(beforeDate, key);
            // 首先判断当前区代码下面存在不存在
            if (areaResourceReport != null) {// 如果不等于空，就证明当前日期下的地区已经存在
                /*
                 * areaResourceReport .setId(areaResourceReport.getId());
                 */
            } else {
                areaResourceReport = new AreaResourceReport();
            }

            areaResourceReport.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
            areaResourceReport.setIntDate(beforeDate);
            areaResourceReport.setAreaIdDistrict(key); // 区代码
            yxyArea = yxyAreaRepository.findByAreaId(key);
            if (yxyArea != null) {
                areaResourceReport.setAreaNameDistrict(yxyArea.getAreaName()); // 区名称
                areaResourceReport.setAreaIdCity(yxyArea.getAreaPId()); // 市代码
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaNameCity(yxyArea.getAreaName()); // 市名称
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaIdProvince(yxyArea.getAreaId()); // 省代码
                yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
            } else {
                yxyArea = null;
            }
            if (yxyArea != null) {
                areaResourceReport.setAreaNameProvince(yxyArea.getAreaName());// 省名称
            }
            areaResourceReport.setWeikeCount(Long.valueOf(map.get(key).toString())); // 资源总共
            /*
             * for (String key2 : map2.keySet()) { if (key.equals(key2)) {
             * areaResourceReport.setShareResCount(Long.valueOf(map2.get(key2).
             * toString()));// 资源共享 } } for (String key3 : map3.keySet()) { if
             * (key.equals(key3)) {
             * areaResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).
             * toString()));// 微课总量 } }
             */
            for (String key4 : map4.keySet()) {
                if (key.equals(key4)) {
                    areaResourceReport.setShareWeikeCount(Long.valueOf(map4.get(key4).toString()));// 微课共享
                }
            }
            if (areaResourceReport.getResCount() == null) {
                areaResourceReport.setResCount(0l);
            }
            if (areaResourceReport.getShareResCount() == null) {
                areaResourceReport.setShareResCount(0l);
            }
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
            // HH:mm:ss");
            areaResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            areaResourceReportRepository.save(areaResourceReport);
        }
    }

    /**
     * 统计学校每天的资源总数
     * 
     * @throws ParseException
     */
    @Override
    public void ywStatisticsResourceSchoolEs(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                .execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
        // 统计资源共享数量
        Map<String, Object> map2 = this.staticsShareDayCount2(startDate, endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计微课总共数量
        // Map<String, Object> map3 = this.staticsWeikeDayCount2(startDate,
        // endDate, beforeDate);// map3的key值指的是学校id，value值指的是微课总共数量
        // 统计微课共享数量
        // Map<String, Object> map4 = this.staticsWeikeShareDayCount2(startDate,
        // endDate, beforeDate);// map4的key值指的是学校id，value值指的是微课共享数量

        // 返回 map里统计的资源总量
        Map<String, Object> map = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        SchoolUploadResourceDay schoolUploadResourceDay = null;
        for (String key : map.keySet()) {
            if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                schoolUploadResourceDay = schoolUploadResDayRepository.findById(key + beforeDate);
                if (schoolUploadResourceDay != null) {
                    // schoolUploadResourceDay =
                    // schoolUploadResDayRepository.findBySchoolIdAndIntDate(key,
                    // beforeDate)
                    // .get(0);
                } else {
                    schoolUploadResourceDay = new SchoolUploadResourceDay();
                    schoolUploadResourceDay.setId(key + beforeDate);// 是由学校id和日期拼合而成
                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                            schoolUploadResourceDay.setIntDate(beforeDate);
                            Integer intMonth = Integer.parseInt(beforeDate.toString().substring(0, 6));
                            schoolUploadResourceDay.setIntMonth(intMonth);
                            schoolUploadResourceDay.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                            schoolUploadResourceDay.setSchoolId(key);
                            schoolUploadResourceDay.setSchoolNick(reList.getBody().get("schoolNick"));
                            schoolUploadResourceDay.setResCount(Long.valueOf(map.get(key).toString()));
                            /*
                             * schoolUploadResourceReport.setSchoolId(reList.
                             * getBody (). get("schoolId"));
                             * schoolUploadResourceReport.setSchoolNick(reList.
                             * getBody() .get("schoolNick"));
                             * schoolUploadResourceReport.setAreaIdProvince(
                             * reList. getBody().get("areaIdProvince"));
                             * schoolUploadResourceReport.setAreaNameProvince(
                             * reList. getBody().get("areaNameProvince"));
                             * schoolUploadResourceReport.setAreaIdCity(reList.
                             * getBody() .get("areaIdCity"));
                             * schoolUploadResourceReport.setAreaNameCity(
                             * reList. getBody ().get("areaNameCity"));
                             * schoolUploadResourceReport.setAreaIdDistrict(
                             * reList. getBody().get("areaIdDistrict"));
                             * schoolUploadResourceReport.setAreaNameDistrict(
                             * reList. getBody().get("areaNameDistrict"));
                             */
                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                }

            }
            schoolUploadResourceDay.setResCount(Long.valueOf(map.get(key).toString()));// 资源总数量
            for (String key2 : map2.keySet()) {
                if (key.equals(key2)) {
                    schoolUploadResourceDay.setShareResCount(Long.valueOf(map2.get(key2).toString())); // 资源共享数量
                }
            }
            /*
             * for (String key3 : map3.keySet()) { if (key.equals(key3)) {
             * schoolUploadResourceDay.setWeikeCount(Long.valueOf(map3.get(key3)
             * .toString())); // 微课总共数量 } } for (String key4 : map4.keySet()) {
             * if (key.equals(key4)) {
             * schoolUploadResourceDay.setShareWeikeCount(Long.valueOf(map4.get(
             * key4).toString())); // 微课共享数量 } }
             */
            if (schoolUploadResourceDay.getWeikeCount() == null) {
                schoolUploadResourceDay.setWeikeCount(0l);
            }
            if (schoolUploadResourceDay.getShareWeikeCount() == null) {
                schoolUploadResourceDay.setShareWeikeCount(0l);
            }
            /*
             * if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
             * ResponseEntity<List<String>> reList = new
             * RestTemplate().exchange( yxyApiYxUrl + "/comm/school/type/id/" +
             * key, HttpMethod.GET, null, new
             * ParameterizedTypeReference<List<String>>() { }); if (reList !=
             * null && reList.getBody() != null && reList.getBody().size() > 0)
             * { schoolUploadResourceReport.setStage(reList.getBody()); } }
             */
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
            // HH:mm:ss");
            schoolUploadResourceDay.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            schoolUploadResDayRepository.save(schoolUploadResourceDay);
        }
        this.ywStatisticsWeikeSchoolEs(startDate, endDate, beforeDate);
    }

    /**
     * 统计学校每天的微课总数
     * 
     * @throws ParseException
     */
    private void ywStatisticsWeikeSchoolEs(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                .execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
        // 统计资源共享数量
        // Map<String, Object> map2 = this.staticsShareDayCount2(startDate,
        // endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计微课总共数量
        // Map<String, Object> map3 = this.staticsWeikeDayCount2(startDate,
        // endDate, beforeDate);// map3的key值指的是学校id，value值指的是微课总共数量
        // 统计微课共享数量
        Map<String, Object> map4 = this.staticsWeikeShareDayCount2(startDate, endDate, beforeDate);// map4的key值指的是学校id，value值指的是微课共享数量

        // 返回 map里统计的资源总量
        Map<String, Object> map = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        SchoolUploadResourceDay schoolUploadResourceDay = null;
        for (String key : map.keySet()) {
            if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                schoolUploadResourceDay = schoolUploadResDayRepository.findById(key + beforeDate);
                if (schoolUploadResourceDay != null) {
                    // schoolUploadResourceDay =
                    // schoolUploadResDayRepository.findBySchoolIdAndIntDate(key,
                    // beforeDate)
                    // .get(0);
                } else {
                    schoolUploadResourceDay = new SchoolUploadResourceDay();
                    schoolUploadResourceDay.setId(key + beforeDate);// 是由学校id和日期拼合而成
                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                            schoolUploadResourceDay.setIntDate(beforeDate);
                            Integer intMonth = Integer.parseInt(beforeDate.toString().substring(0, 6));
                            schoolUploadResourceDay.setIntMonth(intMonth);
                            schoolUploadResourceDay.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                            schoolUploadResourceDay.setSchoolId(key);
                            schoolUploadResourceDay.setSchoolNick(reList.getBody().get("schoolNick"));
                            schoolUploadResourceDay.setResCount(Long.valueOf(map.get(key).toString()));
                            /*
                             * schoolUploadResourceReport.setSchoolId(reList.
                             * getBody (). get("schoolId"));
                             * schoolUploadResourceReport.setSchoolNick(reList.
                             * getBody() .get("schoolNick"));
                             * schoolUploadResourceReport.setAreaIdProvince(
                             * reList. getBody().get("areaIdProvince"));
                             * schoolUploadResourceReport.setAreaNameProvince(
                             * reList. getBody().get("areaNameProvince"));
                             * schoolUploadResourceReport.setAreaIdCity(reList.
                             * getBody() .get("areaIdCity"));
                             * schoolUploadResourceReport.setAreaNameCity(
                             * reList. getBody ().get("areaNameCity"));
                             * schoolUploadResourceReport.setAreaIdDistrict(
                             * reList. getBody().get("areaIdDistrict"));
                             * schoolUploadResourceReport.setAreaNameDistrict(
                             * reList. getBody().get("areaNameDistrict"));
                             */
                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                }

            }
            // schoolUploadResourceReport(Long.valueOf(map.get(key).toString()));//资源总数量
            schoolUploadResourceDay.setWeikeCount(Long.valueOf(map.get(key).toString()));// 微课总数量
            /*
             * for (String key2 : map2.keySet()) { if (key.equals(key2)) {
             * schoolUploadResourceDay.setShareResCount(Long.valueOf(map2.get(
             * key2).toString())); // 资源共享数量 } } for (String key3 :
             * map3.keySet()) { if (key.equals(key3)) {
             * schoolUploadResourceDay.setWeikeCount(Long.valueOf(map3.get(key3)
             * .toString())); // 微课总共数量 } }
             */
            for (String key4 : map4.keySet()) {
                if (key.equals(key4)) {
                    schoolUploadResourceDay.setShareWeikeCount(Long.valueOf(map4.get(key4).toString())); // 微课共享数量
                }
            }
            if (schoolUploadResourceDay.getResCount() == null) {
                schoolUploadResourceDay.setResCount(0l);
            }
            if (schoolUploadResourceDay.getShareResCount() == null) {
                schoolUploadResourceDay.setShareResCount(0l);
            }
            /*
             * if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
             * ResponseEntity<List<String>> reList = new
             * RestTemplate().exchange( yxyApiYxUrl + "/comm/school/type/id/" +
             * key, HttpMethod.GET, null, new
             * ParameterizedTypeReference<List<String>>() { }); if (reList !=
             * null && reList.getBody() != null && reList.getBody().size() > 0)
             * { schoolUploadResourceReport.setStage(reList.getBody()); } }
             */
            // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
            // HH:mm:ss");
            schoolUploadResourceDay.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            schoolUploadResDayRepository.save(schoolUploadResourceDay);
        }
    }

    /**
     * 统计资源共享数量
     * 
     * @return
     */
    private Map<String, Object> staticsShareCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计资源共享数量
     * 
     * 20171218 修改
     * 
     * @return
     */
    private Map<String, Object> staticsShareCountNew() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课总共数量
     * 
     * @return
     */
    private Map<String, Object> staticsWeikeCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课总共数量
     * 
     * 20171218 修改
     * 
     * @return
     */
    private Map<String, Object> staticsWeikeCountNew() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课共享数量
     * 
     * @return
     */
    private Map<String, Object> staticsWeikeShareCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课共享数量
     * 
     * 20171218 修改
     * 
     * @return
     */
    private Map<String, Object> staticsWeikeShareCountNew() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计用户共享资源数量
     * 
     * @return
     */
    private Map<String, Object> userStaticsShareCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        Map<String, Object> mapZong = new HashMap<String, Object>();

        TermsBuilder uploaderSchoolIdTermsBuilder = AggregationBuilders.terms("uploaderSchoolIdAgg").field("uploaderSchoolId").size(25000);
        TermsBuilder uploaderIdTermsBuilder = AggregationBuilders.terms("uploaderIdAgg").field("uploaderId").size(25000);
        uploaderSchoolIdTermsBuilder.subAggregation(uploaderIdTermsBuilder);
        searchRequestBuilder.addAggregation(uploaderSchoolIdTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms uploaderSchoolIdTerms = (StringTerms) aggMap.get("uploaderSchoolIdAgg");
        Iterator<Bucket> uploaderSchoolIdBucketIt = uploaderSchoolIdTerms.getBuckets().iterator();
        Object[] objs = null;
        while (uploaderSchoolIdBucketIt.hasNext()) {
            Bucket gradeBucket = uploaderSchoolIdBucketIt.next();
            // System.out.println(gradeBucket.getKey() + "年级有" +
            // gradeBucket.getDocCount() + "个学生。");
            StringTerms classTerms = (StringTerms) gradeBucket.getAggregations().asMap().get("uploaderIdAgg");
            Iterator<Bucket> classBucketIt = classTerms.getBuckets().iterator();
            objs = new Object[2];
            objs[0] = gradeBucket.getKey();// 学校id
            while (classBucketIt.hasNext()) {
                Bucket classBucket = classBucketIt.next();
                long value = classBucket.getDocCount();
                objs[1] = classBucket.getKey(); // 教师id
                // System.out.println(gradeBucket.getKey() + "学校" + objs[1] +
                // "教师。" + " 有多少资源：" + value);
                mapZong.put(objs[0] + "," + objs[1], value);
            }
            System.out.println();
        }

        /*
         * SearchRequestBuilder searchRequestBuilder =
         * et.getClient().prepareSearch("yxy_res").setTypes("resource");
         * searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
         * TermsBuilder gradeTermsBuilder =
         * AggregationBuilders.terms("phaseIdAgg").field("uploaderId").size(
         * 25000); searchRequestBuilder.addAggregation(gradeTermsBuilder);
         * SearchResponse sr =
         * searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet()
         * ; Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
         * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
         * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
         * 
         * // 返回 Map<String, Object> map = new HashMap<String, Object>(); while
         * (gradeBucketIt.hasNext()) { Bucket gradeBucket =
         * gradeBucketIt.next(); String key = (String) gradeBucket.getKey();
         * long value = gradeBucket.getDocCount(); map.put(key, value); }
         */
        return mapZong;
    }

    /**
     * 统计用户微课总共数量
     * 
     * @return
     */
    private void userStaticsWeikeCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        Map<String, Object> mapZong = new HashMap<String, Object>();

        TermsBuilder uploaderSchoolIdTermsBuilder = AggregationBuilders.terms("uploaderSchoolIdAgg").field("uploaderSchoolId").size(25000);
        TermsBuilder uploaderIdTermsBuilder = AggregationBuilders.terms("uploaderIdAgg").field("uploaderId").size(25000);
        uploaderSchoolIdTermsBuilder.subAggregation(uploaderIdTermsBuilder);
        searchRequestBuilder.addAggregation(uploaderSchoolIdTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms uploaderSchoolIdTerms = (StringTerms) aggMap.get("uploaderSchoolIdAgg");
        Iterator<Bucket> uploaderSchoolIdBucketIt = uploaderSchoolIdTerms.getBuckets().iterator();
        Object[] objs = null;
        while (uploaderSchoolIdBucketIt.hasNext()) {
            Bucket gradeBucket = uploaderSchoolIdBucketIt.next();
            System.out.println(gradeBucket.getKey() + "年级有" + gradeBucket.getDocCount() + "个学生。");
            StringTerms classTerms = (StringTerms) gradeBucket.getAggregations().asMap().get("uploaderIdAgg");
            Iterator<Bucket> classBucketIt = classTerms.getBuckets().iterator();
            objs = new Object[2];
            objs[0] = gradeBucket.getKey();// 学校id
            while (classBucketIt.hasNext()) {
                Bucket classBucket = classBucketIt.next();
                long value = classBucket.getDocCount();
                objs[1] = classBucket.getKey(); // 教师id
                System.out.println(gradeBucket.getKey() + "学校" + objs[1] + "教师。" + " 有多少资源：" + value);
                mapZong.put(objs[0] + "," + objs[1], value);
            }
            System.out.println();
        }
        UserUploadResourceTotal userUploadResourceTotal = null;
        String userId = null;
        String schoolId = null;
        for (String shuliang : mapZong.keySet()) {
            Object[] objs2 = shuliang.split(",");
            userId = objs2[1].toString();
            schoolId = objs2[0].toString();
            if (StringUtils.isNotBlank(userId)) {// 判断用户id是否空
                userUploadResourceTotal = userUploadResourceTotalRepository.findOne(userId + schoolId);
                if (userUploadResourceTotal != null) {
                    // userUploadResourceTotal.setId(userUploadResourceTotalRepository.findByUserId(userId).getId());
                } else {
                    userUploadResourceTotal = new UserUploadResourceTotal();
                    userUploadResourceTotal.setId(userId + schoolId);

                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/user/username/" + userId, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                            userUploadResourceTotal.setUserNick(reList.getBody().get("nickname"));
                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                    userUploadResourceTotal.setUserId(userId);
                    userUploadResourceTotal.setSchoolId(schoolId);
                    if (StringUtils.isNotBlank(schoolId)) {// 判断学校id是否空
                        try {
                            ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + schoolId, HttpMethod.GET, null,
                                    new ParameterizedTypeReference<Map<String, String>>() {
                                    });
                            if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                                userUploadResourceTotal.setSchoolNick(reList.getBody().get("schoolNick"));
                            }
                        } catch (Exception e) {
                            LOGGER.info("错误日志" + e.getMessage());
                        }
                    }

                }

            }
            userUploadResourceTotal.setStatisticsDate(DateUtils.getBeforeDay(new Date()));

            // 统计用户微课共享数量
            Map<String, Object> map4 = this.userStaticsWeikeShareCount();
            // 用户总共微课数量
            userUploadResourceTotal.setWeikeCount(Long.valueOf(mapZong.get(shuliang).toString()));
            if (userUploadResourceTotal.getWeikeCount() == null) {
                userUploadResourceTotal.setWeikeCount(0l);
            }
            // 用户共享资源数量
            for (String key2 : map4.keySet()) {
                if (shuliang.equals(key2)) {
                    userUploadResourceTotal.setShareWeikeCount(Long.valueOf(map4.get(key2).toString()));
                }
            }
            if (userUploadResourceTotal.getShareWeikeCount() == null) {
                userUploadResourceTotal.setShareWeikeCount(0l);
            }
            if (userUploadResourceTotal.getResCount() == null) {
                userUploadResourceTotal.setResCount(0l);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            userUploadResourceTotal.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            userUploadResourceTotalRepository.save(userUploadResourceTotal);
        }

        /*
         * List<UserUploadResourceTotal> userUploadIds =
         * userUploadResourceTotalRepository.findAll(); List<String>
         * userUploadId = new ArrayList<String>(); for (UserUploadResourceTotal
         * userUploadResourceTotal2 : userUploadIds) {
         * userUploadId.add(userUploadResourceTotal2.getId()); }
         * UserUploadResourceTotal userUploadResourceTo = null; for (String id :
         * userUploadId) { userUploadResourceTo =
         * userUploadResourceTotalRepository.findOne(id); if
         * (userUploadResourceTo.getResCount() == null) {
         * userUploadResourceTo.setResCount(0l); } if
         * (userUploadResourceTo.getShareResCount() == null) {
         * userUploadResourceTo.setShareResCount(0l); } if
         * (userUploadResourceTo.getWeikeCount() == null) {
         * userUploadResourceTo.setWeikeCount(0l); } if
         * (userUploadResourceTo.getShareWeikeCount() == null) {
         * userUploadResourceTo.setShareWeikeCount(0l); }
         * userUploadResourceTotalRepository.save(userUploadResourceTo); }
         */
        // 统计用户微课总共数量
        /*
         * for (String key3 : mapZong.keySet()) { if (shuliang.equals(key3)) {
         * userUploadResourceTotal.setWeikeCount(Long.valueOf(map3.get(key3).
         * toString())); } } if (userUploadResourceTotal.getWeikeCount() ==
         * null) { userUploadResourceTotal.setWeikeCount(0l); } // 统计用户微课共享数量
         * for (String key4 : map4.keySet()) { if (shuliang.equals(key4)) {
         * userUploadResourceTotal.setShareWeikeCount(Long.valueOf(map4.get(key4
         * ).toString())); } } if (userUploadResourceTotal.getShareWeikeCount()
         * == null) { userUploadResourceTotal.setShareWeikeCount(0l); }
         */

        /*
         * TermsBuilder gradeTermsBuilder =
         * AggregationBuilders.terms("phaseIdAgg").field("uploaderId").size(
         * 25000); searchRequestBuilder.addAggregation(gradeTermsBuilder);
         * SearchResponse sr =
         * searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet()
         * ; Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
         * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
         * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
         */

        // 返回
        /*
         * while (gradeBucketIt.hasNext()) { Bucket gradeBucket =
         * gradeBucketIt.next(); String key = (String) gradeBucket.getKey();
         * long value = gradeBucket.getDocCount(); map.put(key, value); }
         */

    }

    /**
     * 统计用户微课共享数量
     * 
     * @return
     */
    private Map<String, Object> userStaticsWeikeShareCount() {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);

        Map<String, Object> mapZong = new HashMap<String, Object>();

        TermsBuilder uploaderSchoolIdTermsBuilder = AggregationBuilders.terms("uploaderSchoolIdAgg").field("uploaderSchoolId").size(25000);
        TermsBuilder uploaderIdTermsBuilder = AggregationBuilders.terms("uploaderIdAgg").field("uploaderId").size(25000);
        uploaderSchoolIdTermsBuilder.subAggregation(uploaderIdTermsBuilder);
        searchRequestBuilder.addAggregation(uploaderSchoolIdTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms uploaderSchoolIdTerms = (StringTerms) aggMap.get("uploaderSchoolIdAgg");
        Iterator<Bucket> uploaderSchoolIdBucketIt = uploaderSchoolIdTerms.getBuckets().iterator();
        Object[] objs = null;
        while (uploaderSchoolIdBucketIt.hasNext()) {
            Bucket gradeBucket = uploaderSchoolIdBucketIt.next();
            System.out.println(gradeBucket.getKey() + "年级有" + gradeBucket.getDocCount() + "个学生。");
            StringTerms classTerms = (StringTerms) gradeBucket.getAggregations().asMap().get("uploaderIdAgg");
            Iterator<Bucket> classBucketIt = classTerms.getBuckets().iterator();
            objs = new Object[2];
            objs[0] = gradeBucket.getKey();// 学校id
            while (classBucketIt.hasNext()) {
                Bucket classBucket = classBucketIt.next();
                long value = classBucket.getDocCount();
                objs[1] = classBucket.getKey(); // 教师id
                System.out.println(gradeBucket.getKey() + "学校" + objs[1] + "教师。" + " 有多少资源：" + value);
                mapZong.put(objs[0] + "," + objs[1], value);
            }
            System.out.println();
        }
        /*
         * TermsBuilder gradeTermsBuilder =
         * AggregationBuilders.terms("phaseIdAgg").field("uploaderId").size(
         * 25000); searchRequestBuilder.addAggregation(gradeTermsBuilder);
         * SearchResponse sr =
         * searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet()
         * ; Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
         * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
         * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
         * 
         * // 返回 Map<String, Object> map = new HashMap<String, Object>(); while
         * (gradeBucketIt.hasNext()) { Bucket gradeBucket =
         * gradeBucketIt.next(); String key = (String) gradeBucket.getKey();
         * long value = gradeBucket.getDocCount(); map.put(key, value); }
         */
        return mapZong;
    }

    /**
     * 统计每天资源共享数量
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsShareDayCount(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        searchRequestBuilder.setQuery(boolQueryBuilder);// .setPostFilter(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()));
        SearchResponse sr = searchRequestBuilder.execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课总共数量
     * 
     * @return
     * @throws ParseException
     */
    /*
     * private Map<String, Object> staticsWeikeDayCount(String startDate, String
     * endDate, Integer beforeDate) throws ParseException { BoolQueryBuilder
     * boolQueryBuilder = new BoolQueryBuilder(); TermQueryBuilder builderType2
     * = new TermQueryBuilder("typeId", "yx14");
     * 
     * TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
     * boolQueryBuilder.must(builderType2); boolQueryBuilder.must(builderType);
     * SearchRequestBuilder searchRequestBuilder =
     * et.getClient().prepareSearch("yxy_res").setTypes("resource"); //
     * searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").
     * format("yyyy-MM-dd //
     * HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
     * searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
     * TermsBuilder gradeTermsBuilder =
     * AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000)
     * ; searchRequestBuilder.addAggregation(gradeTermsBuilder); SearchResponse
     * sr = searchRequestBuilder.setQuery(boolQueryBuilder)
     * .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.
     * formatStrDate4(beforeDate).getTime())) .execute().actionGet();
     * Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
     * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
     * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
     * 
     * // 返回 Map<String, Object> map = new HashMap<String, Object>(); while
     * (gradeBucketIt.hasNext()) { Bucket gradeBucket = gradeBucketIt.next();
     * String key = (String) gradeBucket.getKey(); long value =
     * gradeBucket.getDocCount(); map.put(key, value); } return map; }
     */

    /**
     * 统计微课共享数量
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsWeikeShareDayCount(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        searchRequestBuilder.setQuery(boolQueryBuilder);// .setPostFilter(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()));
        SearchResponse sr = searchRequestBuilder.execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计资源共享数量
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsShareDayCount2(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                .execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 统计微课总共数量
     * 
     * @return
     * @throws ParseException
     */
    /*
     * private Map<String, Object> staticsWeikeDayCount2(String startDate,
     * String endDate, Integer beforeDate) throws ParseException {
     * BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
     * TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
     * 
     * TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
     * boolQueryBuilder.must(builderType2); boolQueryBuilder.must(builderType);
     * SearchRequestBuilder searchRequestBuilder =
     * et.getClient().prepareSearch("yxy_res").setTypes("resource"); //
     * searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").
     * format("yyyy-MM-dd //
     * HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
     * searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
     * TermsBuilder gradeTermsBuilder =
     * AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(
     * 25000); searchRequestBuilder.addAggregation(gradeTermsBuilder);
     * SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
     * .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.
     * formatStrDate4(beforeDate).getTime())) .execute().actionGet();
     * Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
     * StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
     * Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
     * 
     * // 返回 Map<String, Object> map = new HashMap<String, Object>(); while
     * (gradeBucketIt.hasNext()) { Bucket gradeBucket = gradeBucketIt.next();
     * String key = (String) gradeBucket.getKey(); long value =
     * gradeBucket.getDocCount(); map.put(key, value); } return map; }
     */

    /**
     * 统计微课共享数量
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsWeikeShareDayCount2(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                .execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /*************************************** 新修改 ********************************************/
    /**
     * 
     * 学校资源总数统计
     * 
     * 20171218 修改
     * 
     */
    public void schoolStatisticsTotalNewEs(Integer date) {
        Long start = System.currentTimeMillis();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder1 = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder1);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        // 统计资源共享数量
        Map<String, Object> map2 = this.staticsShareCountNew();// map2的key值指的是学校id，value值指的是共享资源总量
        // 统计微课总共数量
        Map<String, Object> map3 = this.staticsWeikeCountNew();
        // 统计微课共享数量
        Map<String, Object> map4 = this.staticsWeikeShareCountNew();

        // 返回 map里统计的资源总量
        Map<String, Object> mapschoolId2 = new HashMap<String, Object>();
        // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            mapschoolId2.put(key, value);
        }
        SchoolUploadResourceReport schoolUploadResourceReport = null;
        for (String key : map.keySet()) {

            // 按学校统计备课包总数量
            Long lectureCount = (long) 0;
            Long shareLectureCount = (long) 0;
            List<SchoolUploadResourceMonth> resourceMonthList = schoolUploadResourceMonthRepository.findBySchoolId(key);

            for (SchoolUploadResourceMonth schoolUploadResourceMonth : resourceMonthList) {
                lectureCount += schoolUploadResourceMonth.getLectureCount();
                shareLectureCount += schoolUploadResourceMonth.getShareLectureCount();
            }

            schoolUploadResourceReport = schoolUploadResourceReportRepository.findBySchoolId(key);
            if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                if (schoolUploadResourceReport != null) {
                    // schoolUploadResourceReport
                    // .setId(schoolUploadResourceReportRepository.findBySchoolId(key).getId());
                } else {
                    schoolUploadResourceReport = new SchoolUploadResourceReport();
                    schoolUploadResourceReport.setId(key);
                    schoolUploadResourceReport.setSchoolId(key);

                    try {
                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {

                            schoolUploadResourceReport.setSchoolNick(reList.getBody().get("schoolNick"));
                            schoolUploadResourceReport.setAreaIdProvince(reList.getBody().get("areaIdProvince"));
                            schoolUploadResourceReport.setAreaNameProvince(reList.getBody().get("areaNameProvince"));
                            schoolUploadResourceReport.setAreaIdCity(reList.getBody().get("areaIdCity"));
                            schoolUploadResourceReport.setAreaNameCity(reList.getBody().get("areaNameCity"));
                            schoolUploadResourceReport.setAreaIdDistrict(reList.getBody().get("areaIdDistrict"));
                            schoolUploadResourceReport.setAreaNameDistrict(reList.getBody().get("areaNameDistrict"));

                        }
                    } catch (Exception e) {
                        LOGGER.info("错误日志" + e.getMessage());
                    }

                    if (StringUtils.isNotBlank(key)) {// 判断学校id是否空
                        try {
                            // 远程去yx查询学校学段
                            HttpHeaders headers = new HttpHeaders();
                            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                            headers.setContentType(type);
                            headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE.toString());
                            Map<String, Object> formMap = new HashMap<String, Object>();
                            formMap.put("schoolId", key);
                            HttpEntity<Map<String, Object>> formEntity = new HttpEntity<Map<String, Object>>(formMap, headers);
                            System.out.println(yxyApiYxUrl + "/comm/statistics/school/stage/srh");
                            StageRespModel httpResult = restTemplate.postForObject(yxyApiYxUrl + "/comm/statistics/school/stage/srh", formEntity, StageRespModel.class);

                            List<String> stageData = httpResult.stageName;
                            schoolUploadResourceReport.setStage(stageData);
                        } catch (Exception e) {
                            LOGGER.info("错误日志" + e.getMessage());
                        }

                    }
                }

            }
            schoolUploadResourceReport.setResCount(Long.valueOf(map.get(key).toString()));// 资源总数量
            for (String key2 : map2.keySet()) {
                if (key.equals(key2)) {
                    schoolUploadResourceReport.setShareResCount(Long.valueOf(map2.get(key2).toString())); // 资源共享数量
                }
            }
            if (schoolUploadResourceReport.getShareResCount() == null) {
                schoolUploadResourceReport.setShareResCount(0l);
            }
            for (String key3 : map3.keySet()) {
                if (key.equals(key3)) {
                    schoolUploadResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).toString())); // 微课总共数量
                }
            }
            if (schoolUploadResourceReport.getWeikeCount() == null) {
                schoolUploadResourceReport.setWeikeCount(0l);
            }
            for (String key4 : map4.keySet()) {
                if (key.equals(key4)) {
                    schoolUploadResourceReport.setShareWeikeCount(Long.valueOf(map4.get(key4).toString())); // 微课共享数量
                }
            }
            if (schoolUploadResourceReport.getShareWeikeCount() == null) {
                schoolUploadResourceReport.setShareWeikeCount(0l);
            }

            // 备课包数量
            schoolUploadResourceReport.setLectureCount(lectureCount);
            // 备课包共享数量
            schoolUploadResourceReport.setShareLectureCount(shareLectureCount);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            schoolUploadResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
            schoolUploadResourceReportRepository.save(schoolUploadResourceReport);
        }

        Long end = System.currentTimeMillis();
        LOGGER.info(" --------- yyy " + (end - start));// 运行完此方法需要134毫秒
        LOGGER.info("xuexiaochangdu--" + map.size());

    }

    /**
     * 统计学校每天的资源总数
     * 
     * 20171218 修改
     * 
     * @throws ParseException
     */
    public void ywStatisticsResourceSchoolNewEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        try {
            LOGGER.info("资源学校跑数据_进service" + startDate + endDate + beforeDate);
            // 一天起止时间
            // Date aDate = DateUtils.formatStrDate4(beforeDate);

            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
            boolQueryBuilder.must(builderType);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start1 = sdf.parse(startDate);
            Date end1 = sdf.parse(endDate);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            // 统计资源共享数量
            Map<String, Object> map2 = this.staticsShareDayCountNew1(startDate, endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量

            LOGGER.info("统计资源数量map");
            // 返回 map里统计的资源总
            Map<String, Object> map = new HashMap<String, Object>();
            // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);
            }
            SchoolUploadResourceDay schoolUploadResourceDay = null;
            List<String> stageData = new ArrayList<String>();

            for (String key : map.keySet()) {

                if (StringUtils.isNotBlank(key)) {// 判断学校id是否空

                    if (key.equals("000000005340c395015369d3bb5623be")) {
                        LOGGER.info("云校师大附属小学出现_日统计" + "_" + beforeDate);
                    }

                    // 远程查学校学段
                    ResponseEntity<List<String>> stageList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/type/id/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
                    });
                    if (stageList != null && stageList.getBody() != null && stageList.getBody().size() > 0) {
                        stageData = stageList.getBody();
                    }

                    schoolUploadResourceDay = schoolUploadResDayRepository.findById(key + beforeDate);
                    if (schoolUploadResourceDay != null) {

                        for (String key2 : map2.keySet()) {
                            if (key.equals(key2)) {
                                schoolUploadResourceDay.setShareResCount(Long.valueOf(map2.get(key2).toString())); // 资源共享数量
                            }
                            if (key.equals("000000005340c395015369d3bb5623be")) {
                                LOGGER.info("云校师大附属小学修改_日统计_资源共享数量" + "_" + Long.valueOf(map2.get(key2).toString()));
                            }

                        }
                        schoolUploadResourceDay.setResCount(Long.valueOf(map.get(key).toString()));// 资源数量

                        if (key.equals("000000005340c395015369d3bb5623be")) {
                            LOGGER.info("云校师大附属小学修改_日统计_资源数量" + "_" + Long.valueOf(map.get(key).toString()));
                        }
                        schoolUploadResDayRepository.save(schoolUploadResourceDay);

                    } else {
                        SchoolUploadResourceDay schoolUploadResourceDay1 = new SchoolUploadResourceDay();

                        try {
                            ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null,
                                    new ParameterizedTypeReference<Map<String, String>>() {
                                    });
                            if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                                Integer intMonth = Integer.parseInt(beforeDate.toString().substring(0, 6));

                                schoolUploadResourceDay1.setId(key + beforeDate);// 是由学校id和日期拼合而成
                                schoolUploadResourceDay1.setIntDate(beforeDate);
                                schoolUploadResourceDay1.setIntMonth(intMonth);
                                schoolUploadResourceDay1.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                                schoolUploadResourceDay1.setSchoolId(key);
                                schoolUploadResourceDay1.setSchoolNick(reList.getBody().get("schoolNick"));
                                schoolUploadResourceDay1.setStage(stageData);

                                schoolUploadResourceDay1.setAreaIdProvince(reList.getBody().get("areaIdProvince"));
                                schoolUploadResourceDay1.setAreaIdCity(reList.getBody().get("areaIdCity"));
                                schoolUploadResourceDay1.setAreaIdDistrict(reList.getBody().get("areaIdDistrict"));
                                schoolUploadResourceDay1.setAreaNameCity(reList.getBody().get("areaNameCity"));
                                schoolUploadResourceDay1.setAreaNameDistrict(reList.getBody().get("areaNameDistrict"));
                                schoolUploadResourceDay1.setAreaNameProvince(reList.getBody().get("areaNameProvince"));

                                for (String key2 : map2.keySet()) {
                                    if (key.equals(key2)) {
                                        schoolUploadResourceDay1.setShareResCount(Long.valueOf(map2.get(key2).toString())); // 资源共享数量
                                    }

                                    if (key.equals("000000005340c395015369d3bb5623be")) {
                                        LOGGER.info("云校师大附属小学新建_日统计_资源共享数量" + "_" + Long.valueOf(map2.get(key2).toString()));
                                    }
                                }
                                schoolUploadResourceDay1.setResCount(Long.valueOf(map.get(key).toString()));// 资源数量
                                if (key.equals("000000005340c395015369d3bb5623be")) {
                                    LOGGER.info("云校师大附属小学新建_日统计_资源数量" + "_" + Long.valueOf(map.get(key).toString()));
                                }

                                schoolUploadResourceDay1.setWeikeCount(0l);// 微课数量
                                schoolUploadResourceDay1.setShareWeikeCount(0l);// 共享微课数量
                                schoolUploadResourceDay1.setLectureCount(0l); // 备课包数量
                                schoolUploadResourceDay1.setShareLectureCount(0l);// 共享备课包数量
                                schoolUploadResDayRepository.save(schoolUploadResourceDay1);

                            }
                        } catch (Exception e) {
                            LOGGER.info("错误日志" + e.getMessage());
                        }

                    }

                }

            }
            LOGGER.info("统计资源数量结束");
            this.ywStatisticsWeikeSchoolNewEs(startDate, endDate, beforeDate);

        } catch (Exception e) {
            // TODO: handle exception
            LOGGER.info("====异常：=====" + e.getMessage());

            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计每日Day 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");
            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());

        }
    }

    protected static class StageRespModel {
        public List<String> stageName;
    }

    /**
     * 
     * 统计学校每天的备课包总数
     *
     * @throws ParseException
     */
    private void ywStatisticsPackSchoolNewEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        try {

            // 一天起止时间
            Date aDate = DateUtils.formatStrDate4(beforeDate);
            Date startTime = DateUtils.getFirstDay(aDate);
            Date endTime = DateUtils.getTimesnight(aDate);

            Criteria criteria = new Criteria();
            criteria.and("createdDate").gte(startTime).lte(endTime);
            AggregationResults<RespModel> groupCountResults = null;
            // criteria.and("areaNameCity").is(queryPattern);

            TypedAggregation<YxyLecturePrePack> aggCount = org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation(YxyLecturePrePack.class, match(criteria), //
                    group("schoolId")//
                            .first("schoolId").as("schoolId") //
                            .first("schoolNick").as("schoolNick") //
                            .first("areaIdProvince").as("areaIdProvince") //
                            .first("areaIdCity").as("areaIdCity") //
                            .first("areaIdDistrict").as("areaIdDistrict") //
            );

            groupCountResults = mt.aggregate(aggCount, ResourceStatisticsEsImpl.RespModel.class);

            if (groupCountResults.getMappedResults() != null) {

                List<String> stageData = new ArrayList<String>();

                for (RespModel model : groupCountResults) {

                    Long lectureCount = mt.count(new Query().addCriteria(Criteria.where("createdDate").gte(startTime).lte(endTime).and("schoolId").is(model.schoolId)), YxyLecturePrePack.class);
                    Long shareLectureCount = mt.count(new Query().addCriteria(Criteria.where("createdDate").gte(startTime).lte(endTime).and("schoolId").is(model.schoolId).and("share").ne(0)), YxyLecturePrePack.class);

                    // 查询学校信息
                    ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + model.schoolId, HttpMethod.GET, null,
                            new ParameterizedTypeReference<Map<String, String>>() {
                            });

                    // 查询学校学段
                    ResponseEntity<List<String>> stageList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/type/id/" + model.schoolId, HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
                    });
                    if (stageList != null && stageList.getBody() != null && stageList.getBody().size() > 0) {
                        stageData = stageList.getBody();
                    }

                    SchoolUploadResourceDay schoolUploadResourceDay;
                    schoolUploadResourceDay = schoolUploadResDayRepository.findById(model.schoolId + beforeDate);
                    if (schoolUploadResourceDay != null) {
                        // 备课包数量
                        schoolUploadResourceDay.setLectureCount(lectureCount);
                        // 共享备课包数量
                        schoolUploadResourceDay.setShareLectureCount(shareLectureCount);
                        schoolUploadResDayRepository.save(schoolUploadResourceDay);
                    } else {
                        SchoolUploadResourceDay schoolUploadResourceDay1 = new SchoolUploadResourceDay();
                        Integer intMonth = Integer.parseInt(beforeDate.toString().substring(0, 6));

                        schoolUploadResourceDay1.setId(model.schoolId + beforeDate);
                        schoolUploadResourceDay1.setIntDate(beforeDate);
                        schoolUploadResourceDay1.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                        schoolUploadResourceDay1.setIntMonth(intMonth);
                        schoolUploadResourceDay1.setSchoolId(model.schoolId);
                        schoolUploadResourceDay1.setSchoolNick(reList.getBody().get("schoolNick"));
                        schoolUploadResourceDay1.setStage(stageData);

                        schoolUploadResourceDay1.setAreaIdProvince(reList.getBody().get("areaIdProvince"));
                        schoolUploadResourceDay1.setAreaIdCity(reList.getBody().get("areaIdCity"));
                        schoolUploadResourceDay1.setAreaIdDistrict(reList.getBody().get("areaIdDistrict"));
                        schoolUploadResourceDay1.setAreaNameCity(reList.getBody().get("areaNameCity"));
                        schoolUploadResourceDay1.setAreaNameDistrict(reList.getBody().get("areaNameDistrict"));
                        schoolUploadResourceDay1.setAreaNameProvince(reList.getBody().get("areaNameProvince"));

                        schoolUploadResourceDay1.setLectureCount(lectureCount); // 备课包数量
                        schoolUploadResourceDay1.setShareLectureCount(shareLectureCount); // 共享备课包数量
                        schoolUploadResourceDay1.setResCount(0l);// 资源数量
                        schoolUploadResourceDay1.setShareResCount(0l);// 共享资源数量
                        schoolUploadResourceDay1.setWeikeCount(0l);// 微课数量
                        schoolUploadResourceDay1.setShareWeikeCount(0l);// 共享微课数量
                        schoolUploadResDayRepository.save(schoolUploadResourceDay1);
                    }

                }
            }

            this.schoolStatisticsResAndPackForWeek(beforeDate);

        } catch (Exception e) {
            // TODO: handle exception

            LOGGER.info("====异常：=====" + e.getMessage());

            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计每日Day(备课包) 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");

            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());
        }

    }

    protected static class RespModel extends YxyApiRespModel {

        // 备课包数量
        public Long lectureCount;
        // 共享备课包数量
        public Long shareLectureCount;
        public String schoolId;
        public String schoolNick;;
        public String areaIdProvince;
        public String areaIdCity;
        public String areaIdDistrict;

    }

    /**
     * 统计学校每天的微课总数
     * 
     * @throws ParseException
     */
    @SuppressWarnings("null")
    private void ywStatisticsWeikeSchoolNewEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        try {

            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
            TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
            boolQueryBuilder.must(builderType2);
            boolQueryBuilder.must(builderType);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start1 = sdf.parse(startDate);
            Date end1 = sdf.parse(endDate);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
            // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                    // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                    .execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            // 统计微课共享数量
            Map<String, Object> map4 = this.staticsWeikeShareDayCount2(startDate, endDate, beforeDate);// map4的key值指的是学校id，value值指的是微课共享数量

            // 返回 map里统计的资源总量
            Map<String, Object> map = new HashMap<String, Object>();
            // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);
            }
            SchoolUploadResourceDay schoolUploadResourceDay = null;
            List<String> stageData = new ArrayList<String>();

            for (String key : map.keySet()) {
                if (StringUtils.isNotBlank(key)) {// 判断学校id是否空

                    schoolUploadResourceDay = schoolUploadResDayRepository.findById(key + beforeDate);
                    if (schoolUploadResourceDay != null) {
                        schoolUploadResourceDay.setWeikeCount(Long.valueOf(map.get(key).toString()));// 微课总数量
                        for (String key4 : map4.keySet()) {
                            if (key.equals(key4)) {
                                schoolUploadResourceDay.setShareWeikeCount(Long.valueOf(map4.get(key4).toString())); // 微课共享数量
                            }
                        }
                        schoolUploadResDayRepository.save(schoolUploadResourceDay);

                    } else {

                        // 查询学校学段
                        ResponseEntity<List<String>> stageList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/type/id/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
                        });
                        if (stageList != null && stageList.getBody() != null && stageList.getBody().size() > 0) {
                            stageData = stageList.getBody();
                        }

                        SchoolUploadResourceDay schoolUploadResourceDay1 = new SchoolUploadResourceDay();

                        ResponseEntity<Map<String, String>> reList = restTemplate.exchange(yxyApiYxUrl + "/comm/school/schoolentity/" + key, HttpMethod.GET, null, new ParameterizedTypeReference<Map<String, String>>() {
                        });
                        if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                            Integer intMonth = Integer.parseInt(beforeDate.toString().substring(0, 6));

                            schoolUploadResourceDay1.setId(key + beforeDate);// 是由学校id和日期拼合而成
                            schoolUploadResourceDay1.setIntDate(beforeDate);
                            schoolUploadResourceDay1.setIntMonth(intMonth);
                            schoolUploadResourceDay1.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                            schoolUploadResourceDay1.setSchoolId(key);
                            schoolUploadResourceDay1.setSchoolNick(reList.getBody().get("schoolNick"));
                            schoolUploadResourceDay1.setStage(stageData);

                            schoolUploadResourceDay1.setAreaIdProvince(reList.getBody().get("areaIdProvince"));
                            schoolUploadResourceDay1.setAreaIdCity(reList.getBody().get("areaIdCity"));
                            schoolUploadResourceDay1.setAreaIdDistrict(reList.getBody().get("areaIdDistrict"));
                            schoolUploadResourceDay1.setAreaNameCity(reList.getBody().get("areaNameCity"));
                            schoolUploadResourceDay1.setAreaNameDistrict(reList.getBody().get("areaNameDistrict"));
                            schoolUploadResourceDay1.setAreaNameProvince(reList.getBody().get("areaNameProvince"));

                            schoolUploadResourceDay1.setWeikeCount(Long.valueOf(map.get(key).toString()));// 微课总数量
                            for (String key4 : map4.keySet()) {
                                if (key.equals(key4)) {
                                    schoolUploadResourceDay1.setShareWeikeCount(Long.valueOf(map4.get(key4).toString())); // 微课共享数量
                                }
                            }
                            schoolUploadResourceDay1.setResCount(0l);// 资源数量
                            schoolUploadResourceDay1.setShareResCount(0l);// 资源共享数量
                            schoolUploadResourceDay1.setLectureCount(0l);// 备课包数量
                            schoolUploadResourceDay1.setShareLectureCount(0l);// 备课包共享数量
                            schoolUploadResDayRepository.save(schoolUploadResourceDay1);
                        }

                    }

                }

            }

            this.ywStatisticsPackSchoolNewEs(startDate, endDate, beforeDate);

        } catch (Exception e) {
            // TODO: handle exception

            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计微课每日Day 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");

            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());
        }
    }

    // 按周统计
    private void schoolStatisticsResAndPackForWeek(Integer beforeDate) throws ParseException {

        try {

            Date newDate = DateUtils.formatStrDate4(beforeDate);

            Integer month = DateUtils.formatDate6(newDate);
            // 当前第几周
            Integer week = DateUtils.getWeekOfYear(newDate);
            // 当前年
            Integer year = DateUtils.year(newDate);

            // 一周的开始时间/结束时间
            int firstDayOfWeek = DateUtils.formatDate4(DateUtils.getMondayOfThisWeek1(newDate));
            int lastDayOfWeek = DateUtils.formatDate4(DateUtils.getSundayOfThisWeek1(newDate));

            LOGGER.info(" 一周的时间" + "_" + firstDayOfWeek + "_" + lastDayOfWeek);

            Criteria criteria = Criteria.where("intDate").gte(firstDayOfWeek).lte(lastDayOfWeek);

            TypedAggregation<SchoolUploadResourceDay> aggregation = org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation(SchoolUploadResourceDay.class,
                    org.springframework.data.mongodb.core.aggregation.Aggregation.match(criteria),
                    org.springframework.data.mongodb.core.aggregation.Aggregation.group("schoolId")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("weikeCount").as("weikeCount")//
                            .sum("shareWeikeCount").as("shareWeikeCount")//
                            .first("schoolId").as("schoolId")//
                            .first("schoolNick").as("schoolNick")//
                            .first("stage").as("stage")//
                            .first("areaIdProvince").as("areaIdProvince")//
                            .first("areaNameProvince").as("areaNameProvince")//
                            .first("areaIdCity").as("areaIdCity")//
                            .first("areaNameCity").as("areaNameCity")//
                            .first("areaIdDistrict").as("areaIdDistrict")//
                            .first("areaNameDistrict").as("areaNameDistrict"));

            AggregationResults<WeekOfYearReportModel> result = mt.aggregate(aggregation, WeekOfYearReportModel.class);

            LOGGER.info("mong语句" + "_" + aggregation);

            List<WeekOfYearReportModel> resAndPackData = result.getMappedResults();

            if (resAndPackData.size() > 0) {
                for (WeekOfYearReportModel weekData : resAndPackData) {

                    if (weekData.schoolId.equals("000000005340c395015369d3bb5623be")) {
                        LOGGER.info("云校师大附属小学出现" + "_" + year + "_" + week);
                    }

                    SchoolUploadResourceWeekOfYearReport weekOfYearReport;
                    String id = weekData.schoolId + "_" + year + "_" + week;

                    weekOfYearReport = schoolUploadResourceWeekOfYearReportRepository.findById(id);

                    // 进行数据更新
                    if (null != weekOfYearReport) {
                        weekOfYearReport.setResCount(weekData.resCount);
                        weekOfYearReport.setShareResCount(weekData.shareResCount);

                        weekOfYearReport.setWeikeCount(weekData.weikeCount);
                        weekOfYearReport.setShareWeikeCount(weekData.shareWeikeCount);

                        weekOfYearReport.setLectureCount(weekData.lectureCount);
                        weekOfYearReport.setShareLectureCount(weekData.shareLectureCount);

                        schoolUploadResourceWeekOfYearReportRepository.save(weekOfYearReport);
                        if (weekData.schoolId.equals("000000005340c395015369d3bb5623be")) {
                            LOGGER.info("按周统计修改保存" + "_" + weekData.resCount + "_" + weekData.shareResCount);
                        }

                    }
                    // 进行数据添加
                    else {

                        SchoolUploadResourceWeekOfYearReport weekOfYearReport1 = new SchoolUploadResourceWeekOfYearReport();
                        weekOfYearReport1.setId(id);
                        weekOfYearReport1.setYear(year);
                        weekOfYearReport1.setMonth(month);
                        weekOfYearReport1.setWeek(week);
                        weekOfYearReport1.setSchoolId(weekData.schoolId);
                        weekOfYearReport1.setSchoolNick(weekData.schoolNick);
                        weekOfYearReport1.setStage(weekData.stage);
                        weekOfYearReport1.setAreaIdCity(weekData.areaIdCity);
                        weekOfYearReport1.setAreaIdDistrict(weekData.areaIdDistrict);
                        weekOfYearReport1.setAreaIdProvince(weekData.areaIdProvince);
                        weekOfYearReport1.setAreaNameCity(weekData.areaNameCity);
                        weekOfYearReport1.setAreaNameDistrict(weekData.areaNameDistrict);
                        weekOfYearReport1.setAreaNameProvince(weekData.areaNameProvince);

                        weekOfYearReport1.setResCount(weekData.resCount);
                        weekOfYearReport1.setShareResCount(weekData.shareResCount);

                        weekOfYearReport1.setWeikeCount(weekData.weikeCount);
                        weekOfYearReport1.setShareWeikeCount(weekData.shareWeikeCount);

                        weekOfYearReport1.setLectureCount(weekData.lectureCount);
                        weekOfYearReport1.setShareLectureCount(weekData.shareLectureCount);

                        if (weekData.schoolId.equals("000000005340c395015369d3bb5623be")) {
                            LOGGER.info("按周统计新建保存" + "_" + weekData.resCount + "_" + weekData.shareResCount);
                        }

                        schoolUploadResourceWeekOfYearReportRepository.save(weekOfYearReport1);

                    }
                }
            }
            schoolStatisticsResAndPackForMonth(beforeDate);
        } catch (Exception e) {
            // TODO: handle exception
            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计每周Week 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");

            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());
        }

    }

    protected static class WeekOfYearReportModel {

        public String schoolId;
        public String schoolNick;
        public List<String> stage;
        public String areaIdCity;
        public String areaIdDistrict;
        public String areaIdProvince;
        public String areaNameCity;
        public String areaNameDistrict;
        public String areaNameProvince;

        public Long resCount;
        public Long shareResCount;

        public Long weikeCount;
        public Long shareWeikeCount;

        public Long lectureCount;
        public Long shareLectureCount;
    }

    /*
     * 每月学校资源和备课包的总数
     * 
     * @see com.china08.yxyapi.service.res.statistics.IResourceStatistics#
     * schoolStatisticsResAndPackForMonth(java.lang.Integer)
     */
    private void schoolStatisticsResAndPackForMonth(Integer beforeDate) throws ParseException {

        try {

            Date newDate = DateUtils.formatStrDate4(beforeDate);
            Integer month = DateUtils.formatDate6(newDate);

            Criteria criteria = Criteria.where("month").is(month);

            TypedAggregation<SchoolUploadResourceWeekOfYearReport> aggregation = org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation(SchoolUploadResourceWeekOfYearReport.class,
                    org.springframework.data.mongodb.core.aggregation.Aggregation.match(criteria),
                    org.springframework.data.mongodb.core.aggregation.Aggregation.group("schoolId")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("weikeCount").as("weikeCount")//
                            .sum("shareWeikeCount").as("shareWeikeCount")//
                            .first("schoolId").as("schoolId")//
                            .first("schoolNick").as("schoolNick")//
                            .first("stage").as("stage")//
                            .first("areaIdProvince").as("areaIdProvince")//
                            .first("areaNameProvince").as("areaNameProvince")//
                            .first("areaIdCity").as("areaIdCity")//
                            .first("areaNameCity").as("areaNameCity")//
                            .first("areaIdDistrict").as("areaIdDistrict")//
                            .first("areaNameDistrict").as("areaNameDistrict"));

            AggregationResults<MonthReportModel> result = mt.aggregate(aggregation, MonthReportModel.class);
            List<MonthReportModel> resAndPackData = result.getMappedResults();

            if (resAndPackData.size() > 0) {
                for (MonthReportModel monthData : resAndPackData) {

                    SchoolUploadResourceMonth monthOfYearReport;
                    String id = monthData.schoolId + "_" + month;

                    monthOfYearReport = schoolUploadResourceMonthRepository.findById(id);

                    // 进行数据更新
                    if (null != monthOfYearReport) {
                        monthOfYearReport.setResCount(monthData.resCount);
                        monthOfYearReport.setShareResCount(monthData.shareResCount);

                        monthOfYearReport.setWeikeCount(monthData.weikeCount);
                        monthOfYearReport.setShareWeikeCount(monthData.shareWeikeCount);

                        monthOfYearReport.setLectureCount(monthData.lectureCount);
                        monthOfYearReport.setShareLectureCount(monthData.shareLectureCount);

                        schoolUploadResourceMonthRepository.save(monthOfYearReport);
                    }
                    // 进行数据添加
                    else {

                        monthOfYearReport = new SchoolUploadResourceMonth();
                        monthOfYearReport.setId(id);
                        monthOfYearReport.setIntMonth(month);
                        monthOfYearReport.setStatisticsDate(new Date());
                        monthOfYearReport.setSchoolId(monthData.schoolId);
                        monthOfYearReport.setSchoolNick(monthData.schoolNick);
                        monthOfYearReport.setStage(monthData.stage);
                        monthOfYearReport.setAreaIdCity(monthData.areaIdCity);
                        monthOfYearReport.setAreaIdDistrict(monthData.areaIdDistrict);
                        monthOfYearReport.setAreaIdProvince(monthData.areaIdProvince);
                        monthOfYearReport.setAreaNameCity(monthData.areaNameCity);
                        monthOfYearReport.setAreaNameDistrict(monthData.areaNameDistrict);
                        monthOfYearReport.setAreaNameProvince(monthData.areaNameProvince);

                        monthOfYearReport.setResCount(monthData.resCount);
                        monthOfYearReport.setShareResCount(monthData.shareResCount);

                        monthOfYearReport.setWeikeCount(monthData.weikeCount);
                        monthOfYearReport.setShareWeikeCount(monthData.shareWeikeCount);

                        monthOfYearReport.setLectureCount(monthData.lectureCount);
                        monthOfYearReport.setShareLectureCount(monthData.shareLectureCount);
                        schoolUploadResourceMonthRepository.save(monthOfYearReport);

                    }
                }
            }

            this.schoolStatisticsResAndPackForTotal(beforeDate);
        } catch (Exception e) {
            // TODO: handle exception
            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计每月Month 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");

            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());
        }

    }

    /*
     * 总共学校资源和备课包的总数
     * 
     * @see com.china08.yxyapi.service.res.statistics.IResourceStatistics#
     * schoolStatisticsResAndPackForMonth(java.lang.Integer)
     */
    private void schoolStatisticsResAndPackForTotal(Integer beforeDate) throws ParseException {

        try {

            TypedAggregation<SchoolUploadResourceMonth> aggregation = org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation(SchoolUploadResourceMonth.class,
                    org.springframework.data.mongodb.core.aggregation.Aggregation.group("schoolId")//
                            .sum("resCount").as("resCount")//
                            .sum("shareResCount").as("shareResCount")//
                            .sum("lectureCount").as("lectureCount")//
                            .sum("shareLectureCount").as("shareLectureCount")//
                            .sum("weikeCount").as("weikeCount")//
                            .sum("shareWeikeCount").as("shareWeikeCount")//
                            .first("schoolId").as("schoolId")//
                            .first("schoolNick").as("schoolNick")//
                            .first("stage").as("stage")//
                            .first("areaIdProvince").as("areaIdProvince")//
                            .first("areaNameProvince").as("areaNameProvince")//
                            .first("areaIdCity").as("areaIdCity")//
                            .first("areaNameCity").as("areaNameCity")//
                            .first("areaIdDistrict").as("areaIdDistrict")//
                            .first("areaNameDistrict").as("areaNameDistrict"));

            AggregationResults<MonthReportModel> result = mt.aggregate(aggregation, MonthReportModel.class);
            List<MonthReportModel> resAndPackData = result.getMappedResults();
            if (resAndPackData.size() > 0) {
                for (MonthReportModel monthData : resAndPackData) {

                    SchoolUploadResourceReport monthOfYearReport;

                    monthOfYearReport = schoolUploadResourceReportRepository.findById(monthData.schoolId);

                    // 进行数据更新
                    if (null != monthOfYearReport) {
                        monthOfYearReport.setResCount(monthData.resCount);
                        monthOfYearReport.setShareResCount(monthData.shareResCount);

                        monthOfYearReport.setWeikeCount(monthData.weikeCount);
                        monthOfYearReport.setShareWeikeCount(monthData.shareWeikeCount);

                        monthOfYearReport.setLectureCount(monthData.lectureCount);
                        monthOfYearReport.setShareLectureCount(monthData.shareLectureCount);

                        schoolUploadResourceReportRepository.save(monthOfYearReport);
                    }
                    // 进行数据添加
                    else {

                        monthOfYearReport = new SchoolUploadResourceReport();
                        monthOfYearReport.setId(monthData.schoolId);
                        monthOfYearReport.setSchoolId(monthData.schoolId);
                        monthOfYearReport.setSchoolNick(monthData.schoolNick);
                        monthOfYearReport.setStage(monthData.stage);
                        monthOfYearReport.setAreaIdCity(monthData.areaIdCity);
                        monthOfYearReport.setAreaIdDistrict(monthData.areaIdDistrict);
                        monthOfYearReport.setAreaIdProvince(monthData.areaIdProvince);
                        monthOfYearReport.setAreaNameCity(monthData.areaNameCity);
                        monthOfYearReport.setAreaNameDistrict(monthData.areaNameDistrict);
                        monthOfYearReport.setAreaNameProvince(monthData.areaNameProvince);

                        monthOfYearReport.setResCount(monthData.resCount);
                        monthOfYearReport.setShareResCount(monthData.shareResCount);

                        monthOfYearReport.setWeikeCount(monthData.weikeCount);
                        monthOfYearReport.setShareWeikeCount(monthData.shareWeikeCount);

                        monthOfYearReport.setLectureCount(monthData.lectureCount);
                        monthOfYearReport.setShareLectureCount(monthData.shareLectureCount);
                        schoolUploadResourceReportRepository.save(monthOfYearReport);

                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            String email = "1605657621@qq.com";
            String header = "资源统计按学校统计总共Total 报错";
            StackTraceElement[] aElements = e.getStackTrace();
            String text = "详细信息：" + e.getMessage();
            LOGGER.info("详细日志:lwd");
            for (StackTraceElement stackTraceElement : aElements) {
                text = text + stackTraceElement + "/n";
            }
            try {
                SendEmailUtil.sendEmailValidate(email, null, header, text);
            } catch (Exception e2) {
                LOGGER.error("lld:发送邮件失败");

            }
            LOGGER.info("详细日志:lwd:" + text);
            LOGGER.info("积分学校错误日志:**********************" + e.getMessage());
        }
    }

    protected static class MonthReportModel {

        public String schoolId;
        public String schoolNick;
        public List<String> stage;
        public String areaIdCity;
        public String areaIdDistrict;
        public String areaIdProvince;
        public String areaNameCity;
        public String areaNameDistrict;
        public String areaNameProvince;

        public Long resCount;
        public Long shareResCount;

        public Long weikeCount;
        public Long shareWeikeCount;

        public Long lectureCount;
        public Long shareLectureCount;
    }

    /**
     * 统计资源共享数量
     * 
     * 20171219 修改
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsShareDayCountNew(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder)
                // .setQuery(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()))
                .execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 学校按天统计 资源共享数量
     * 
     * 20180122 修改
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsShareDayCountNew1(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");
        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.mustNot(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("uploaderSchoolId").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }

    /**
     * 区域统计资源每天的数据
     * 
     * 新修改
     * 
     * @param beforeDate
     * @throws ParseException
     */
    @Override
    public void ywStatisticsResourceAreaForDayNewEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        LOGGER.info("====资源区域统计开始=====");
        try {

            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
            // "yx14");
            TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
            // boolQueryBuilder.mustNot(builderType2);
            boolQueryBuilder.must(builderType);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start1 = sdf.parse(startDate);
            Date end1 = sdf.parse(endDate);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
            // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            searchRequestBuilder.setQuery(boolQueryBuilder); // .setPostFilter(QueryBuilders.rangeQuery("createdDate").from(start1.getTime()).to(end1.getTime()));
            SearchResponse sr = searchRequestBuilder.execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

            // 统计每天资源共享数量
            Map<String, Object> map2 = this.staticsShareDayCountNew(startDate, endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
            // 统计每天微课总共数量
            // Map<String, Object> map3 = this.staticsWeikeDayCount(startDate,
            // endDate, beforeDate);
            // 统计每天微课共享数量
            // Map<String, Object> map4 =
            // this.staticsWeikeShareDayCount(startDate,
            // endDate, beforeDate);

            // 返回 map里统计的资源总量
            Map<String, Object> map = new HashMap<String, Object>();
            // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);
            }

            AreaResourceReport areaResourceReport = null;
            // 每天的资源总量
            YxyArea yxyArea = null;
            for (String key : map.keySet()) {
                areaResourceReport = areaResourceReportRepository.findByIntDateAndAreaIdDistrict(beforeDate, key);
                // 首先判断当前区代码下面存在不存在
                if (areaResourceReport != null) {// 如果不等于空，就证明当前日期下的地区已经存在
                    /*
                     * areaResourceReport .setId(areaResourceReport.getId());
                     */
                } else {
                    areaResourceReport = new AreaResourceReport();
                }

                areaResourceReport.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                areaResourceReport.setIntDate(beforeDate);
                areaResourceReport.setAreaIdDistrict(key); // 区代码
                yxyArea = yxyAreaRepository.findByAreaId(key);
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameDistrict(yxyArea.getAreaName()); // 区名称
                    areaResourceReport.setAreaIdCity(yxyArea.getAreaPId()); // 市代码
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameCity(yxyArea.getAreaName()); // 市名称
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaIdProvince(yxyArea.getAreaId()); // 省代码
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameProvince(yxyArea.getAreaName());// 省名称
                }
                areaResourceReport.setResCount(Long.valueOf(map.get(key).toString())); // 资源总共
                for (String key2 : map2.keySet()) {
                    if (key.equals(key2)) {
                        areaResourceReport.setShareResCount(Long.valueOf(map2.get(key2).toString()));// 资源共享
                    }
                }
                if (areaResourceReport.getWeikeCount() == null) {
                    areaResourceReport.setWeikeCount(0l);
                }
                if (areaResourceReport.getShareWeikeCount() == null) {
                    areaResourceReport.setShareWeikeCount(0l);
                }
                /*
                 * for (String key3 : map3.keySet()) { if (key.equals(key3)) {
                 * areaResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).
                 * toString()));// 微课总量 } } for (String key4 : map4.keySet()) {
                 * if (key.equals(key4)) {
                 * areaResourceReport.setShareWeikeCount(Long.valueOf(map4.get(
                 * key4) .toString()));// 微课共享 } }
                 */
                // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
                // HH:mm:ss");
                areaResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
                areaResourceReportRepository.save(areaResourceReport);
            }
            this.ywStatisticsWeiKeAreaForDayNewEs(startDate, endDate, beforeDate);

        } catch (Exception e) {
            // TODO: handle exception
            LOGGER.info("====异常：=====" + e.getMessage());

            String email = "1605657621@qq.com";
            String header = "资源统计按地区统计每日Day 报错";
            String text = "详细信息：" + e.getMessage();
            SendEmailUtil.sendEmailValidate(email, null, header, text);
        }
    }

    /**
     * 区域统计微课每天的数据
     * 
     * @param beforeDate
     * @throws ParseException
     */
    private void ywStatisticsWeiKeAreaForDayNewEs(String startDate, String endDate, Integer beforeDate) throws ParseException {

        try {

            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
            // "yx14");
            TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
            // boolQueryBuilder.must(builderType2);
            boolQueryBuilder.must(builderType);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start1 = sdf.parse(startDate);
            Date end1 = sdf.parse(endDate);
            boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
            // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            searchRequestBuilder.setQuery(boolQueryBuilder);// .setPostFilter(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()));
            SearchResponse sr = searchRequestBuilder.execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

            // 统计每天资源共享数量
            // Map<String, Object> map2 = this.staticsShareDayCount(startDate,
            // endDate, beforeDate);// map2的key值指的是学校id，value值指的是共享资源总量
            // 统计每天微课总共数量
            // Map<String, Object> map3 = this.staticsWeikeDayCount(startDate,
            // endDate, beforeDate);
            // 统计每天微课共享数量
            Map<String, Object> map4 = this.staticsWeikeShareDayCountNew(startDate, endDate, beforeDate);
            // 返回 map里统计的资源总量
            Map<String, Object> map = new HashMap<String, Object>();
            // 通过对学校id进行分组，将es资源表所有的数据进行统计，封装到map里,key值代表schoolId，value值代表的是每个学校下面的总共资源数
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);
            }

            AreaResourceReport areaResourceReport = null;
            // 每天的资源总量
            YxyArea yxyArea = null;
            for (String key : map.keySet()) {
                areaResourceReport = areaResourceReportRepository.findByIntDateAndAreaIdDistrict(beforeDate, key);
                // 首先判断当前区代码下面存在不存在
                if (areaResourceReport != null) {// 如果不等于空，就证明当前日期下的地区已经存在
                    /*
                     * areaResourceReport .setId(areaResourceReport.getId());
                     */
                } else {
                    areaResourceReport = new AreaResourceReport();
                }

                areaResourceReport.setStatisticsDate(DateUtils.formatStrDate4(beforeDate));
                areaResourceReport.setIntDate(beforeDate);
                areaResourceReport.setAreaIdDistrict(key); // 区代码
                yxyArea = yxyAreaRepository.findByAreaId(key);
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameDistrict(yxyArea.getAreaName()); // 区名称
                    areaResourceReport.setAreaIdCity(yxyArea.getAreaPId()); // 市代码
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameCity(yxyArea.getAreaName()); // 市名称
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaIdProvince(yxyArea.getAreaId()); // 省代码
                    yxyArea = yxyAreaRepository.findByAreaId(yxyArea.getAreaPId());
                } else {
                    yxyArea = null;
                }
                if (yxyArea != null) {
                    areaResourceReport.setAreaNameProvince(yxyArea.getAreaName());// 省名称
                }
                areaResourceReport.setWeikeCount(Long.valueOf(map.get(key).toString())); // 资源总共
                /*
                 * for (String key2 : map2.keySet()) { if (key.equals(key2)) {
                 * areaResourceReport.setShareResCount(Long.valueOf(map2.get(
                 * key2). toString()));// 资源共享 } } for (String key3 :
                 * map3.keySet()) { if (key.equals(key3)) {
                 * areaResourceReport.setWeikeCount(Long.valueOf(map3.get(key3).
                 * toString()));// 微课总量 } }
                 */
                for (String key4 : map4.keySet()) {
                    if (key.equals(key4)) {
                        areaResourceReport.setShareWeikeCount(Long.valueOf(map4.get(key4).toString()));// 微课共享
                    }
                }
                if (areaResourceReport.getResCount() == null) {
                    areaResourceReport.setResCount(0l);
                }
                if (areaResourceReport.getShareResCount() == null) {
                    areaResourceReport.setShareResCount(0l);
                }
                // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd
                // HH:mm:ss");
                areaResourceReport.setLastModifiedDate(Timestamp.valueOf(sdf.format(new Date())));
                areaResourceReportRepository.save(areaResourceReport);
            }
        } catch (Exception e) {
            // TODO: handle exception

            LOGGER.info("====异常：=====" + e.getMessage());

            String email = "1605657621@qq.com";
            String header = "资源区域统计微课每天的数据  报错";
            String text = "详细信息：" + e.getMessage();
            SendEmailUtil.sendEmailValidate(email, null, header, text);
        }
    }

    /**
     * 统计微课共享数量
     * 
     * @return
     * @throws ParseException
     */
    private Map<String, Object> staticsWeikeShareDayCountNew(String startDate, String endDate, Integer beforeDate) throws ParseException {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // TermQueryBuilder builderType2 = new TermQueryBuilder("typeId",
        // "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        // boolQueryBuilder.must(builderType2);
        boolQueryBuilder.must(builderType);
        TermQueryBuilder builderType22 = new TermQueryBuilder("viewScope", 0);
        boolQueryBuilder.mustNot(builderType22);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start1 = sdf.parse(startDate);
        Date end1 = sdf.parse(endDate);
        boolQueryBuilder.must(QueryBuilders.rangeQuery("createdDate").lt(end1.getTime()).gte(start1.getTime()));

        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        // searchRequestBuilder.setQuery(QueryBuilders.rangeQuery("createDate").format("yyyy-MM-dd
        // HH:mm:ss").gt(String.valueOf(startDate)).lt(String.valueOf(endDate)));
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("districtCode").size(25000);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        searchRequestBuilder.setQuery(boolQueryBuilder);// .setPostFilter(QueryBuilders.rangeQuery("createdDate").gt(DateUtils.formatStrDate4(beforeDate).getTime()));
        SearchResponse sr = searchRequestBuilder.execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);
        }
        return map;
    }
}
